//
//  ZMPopViewBg.m
//  FM_Project
//
//  Created by chenzm on 2019/8/8.
//  Copyright © 2019 DL. All rights reserved.
//

#import "ZMPopViewBg.h"


#define popIphone_w [[UIScreen mainScreen] bounds].size.width
#define popIphone_h [[UIScreen mainScreen] bounds].size.height
@interface ZMPopViewBg ()
///半透明背景视图
@property(nonatomic,strong)UIView *alphaVBg;

@end

@implementation ZMPopViewBg{
    UIView *_customView;
}

/**
 @param customView 自定义视图
 */
- (instancetype)initWithCustomView:(UIView *)customView{
    self = [super initWithFrame:CGRectMake(0, 0, kIphone_W, kIphone_H)];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        if (!_alphaVBg) {
            [self addSubview:self.alphaVBg];
        }
        _customView = customView;
        [self addSubview:_customView];
        CGSize size = customView.bounds.size;
        customView.center = self.center;
        customView.size = size;
    }
    return self;
}


#pragma mark - lazyload
-(UIView *)alphaVBg{
    if (!_alphaVBg) {
        _alphaVBg = [UIView new];
        _alphaVBg.frame = CGRectMake(0, 0, popIphone_w, popIphone_h);
        _alphaVBg.backgroundColor = [UIColor blackColor];
        _alphaVBg.alpha = 0.7;
        
    }
    return _alphaVBg;
}

#pragma mark - Methods

/**
 视图显示
 @param view 添加视图到指定的对象，如果为nil时默认为Window
 @param animated 是否添加动画
 */
- (void)showToView:(UIView *)view animation:(BOOL)animated{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    if (!view) {
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        [window addSubview:self];
    }else{
        [view addSubview:self];
        if (view.width != popIphone_h) {
            _customView.center = view.center;
        }
    }
    animated?[self shakeToShow:self]:nil;
}

/**
 视图消失
 @param duration 消失动画的持续事件
 */
- (void)dismissWithDuration:(NSTimeInterval)duration{
    duration = duration == 0?0.4:duration;
    [UIView animateWithDuration:duration
                     animations:^{
                         self.alpha = 0;
                         [self layoutSubviews];
                     } completion:^(BOOL finished) {
                         [self removeFromSuperview];
                     }];
}
///显示
- (void)show:(BOOL)animated{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:self];
    animated?[self shakeToShow:self]:nil;
}
///隐藏
- (void)dismiss{
    [UIView animateWithDuration:0.4
                     animations:^{
                         self.alpha = 0;
                         [self layoutSubviews];
                     } completion:^(BOOL finished) {
                         [self removeFromSuperview];
                     }];
}
///动画
- (void)shakeToShow:(UIView *)aView{
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = 0.2;
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D: CATransform3DMakeScale(0.5, 0.5, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D: CATransform3DMakeScale(0.8, 0.8, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D: CATransform3DMakeScale(1.1, 1.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D: CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    animation.values = values;
    [_customView.layer addAnimation:animation forKey:nil];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesBegan:touches withEvent:event];
    if (_isDismiss) {
        [self dismiss];
    }
}
#pragma mark - UIKeyboardNotification

- (void)keyboardWillChangeFrame:(NSNotification *)notification
{
    NSDictionary *userInfo = notification.userInfo;
    CGRect endFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGRect beginFrame = [userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIViewAnimationCurve curve = [userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];
    
    
    
    void(^animations)(void) = ^{
        [self willShowKeyboardFromFrame:beginFrame toFrame:endFrame];
    };
    
    void(^completion)(BOOL) = ^(BOOL finished){
    };
    
    [UIView animateWithDuration:duration delay:0.0f options:(curve << 16 | UIViewAnimationOptionBeginFromCurrentState) animations:animations completion:completion];
}

- (void)willShowKeyboardFromFrame:(CGRect)beginFrame toFrame:(CGRect)toFrame
{
    CGRect frame = CGRectMake(0, 0, popIphone_w, popIphone_h);
    
    if (beginFrame.origin.y == popIphone_h) {
        
        UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
        UIView *firstResponder = [keyWindow performSelector:@selector(firstResponder)];
        CGRect firstFrame = firstResponder.frame;
        CGFloat firstBottomY = firstFrame.origin.y + CGRectGetHeight(firstFrame);
        CGFloat upY = popIphone_h - (CGRectGetHeight(toFrame) + firstBottomY + 40);
        if (upY < 0) {
            //抬起
            frame.origin.y = upY;
        }else{
            //复位
            
        }
        self.frame = frame;
    } else if (toFrame.origin.y == popIphone_h) {
        self.frame = frame;
    }
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)firstResponder{
    
}

@end
